package wschat.config;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import wschat.tcp.StringProtocolInitalizer;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by alex on 15-1-26.
 */
@Configuration
public class NettyConfig {



    private boolean keepAlive = true;

    private int backlog = 1024;

    private String hostName = "127.0.0.1";
    
    private int tcpPort = 9919;

    @Autowired
    @Qualifier("springProtocolInitializer")
    private StringProtocolInitalizer protocolInitalizer;

    @Bean
    @Qualifier("clientBootstrap")
    @Description("client bootstrap")
    public Bootstrap bootstrap(){
        
        Bootstrap b = new Bootstrap();
        b.group(loopGroup())
                .channel(NioSocketChannel.class)
                .handler(protocolInitalizer);
        
        Map<ChannelOption<?>,Object> tcpChannelOptions = tcpChannelOptions();
        Set<ChannelOption<?>> keySet = tcpChannelOptions.keySet();

        for (@SuppressWarnings("rawtypes")
        ChannelOption option : keySet) {
            b.option(option, tcpChannelOptions.get(option));
        }
        return b;
    }
    
    

    @Bean(name = "tcpChannelOptions")
    public Map<ChannelOption<?>,Object> tcpChannelOptions(){
        Map<ChannelOption<?>,Object> options = new HashMap<ChannelOption<?>,Object>();
       // options.put(ChannelOption.SO_KEEPALIVE, keepAlive);
      //  options.put(ChannelOption.SO_BACKLOG, backlog);
        return options;
    }

    @Bean()
    @Qualifier("remoteAddress")
    public InetSocketAddress tcpPort(){
        return new InetSocketAddress(hostName,tcpPort);
    }

    @Bean
    public NioEventLoopGroup loopGroup() {
        return new NioEventLoopGroup();
    }

    @Bean(name = "stringEncoder")
    public StringEncoder stringEncoder(){
        return new StringEncoder();
    }

    @Bean(name = "stringDecoder")
    public StringDecoder stringDecoder(){
        return new StringDecoder();
    }
}
